import path from 'path'
import fs from 'fs'
import AdmZip from 'adm-zip'
import { remove } from '../utils/index'

/**
 * 将文件解压到制定目录
 * @param input input path or stream
 * @param output output path
 * @param strip strip output path
 */
export const extract = async (input: string, output: string, strip = 0): Promise<void> => {
  let fileName = '' // 过滤文件名
  // 将所有文件路径提前
  const zip = new AdmZip(input)
  strip === 0 || zip.getEntries().forEach(entry => {
    const items = entry.entryName.split(/\/|\\/)
    const start = Math.min(strip, items.length - 1)
    const stripped = items.slice(start).join('/')
    if (stripped === '') {
      fileName = items[0]
    } else {
      entry.entryName = stripped
    }
  })

  // https://github.com/cthackers/adm-zip/issues/389
  // https://github.com/cthackers/adm-zip/issues/407#issuecomment-990086783
  // keep original file permissions
  // 将内容解压出来
  zip.extractAllTo(output, true)

  // 删除文件名
  await remove(path.join(output, fileName))

  // 删除零时文件
  await remove(path.dirname(input))
}

/**
 * 重写模板package.json项目名称
 * @param targetDir 项目名称
 * @param targetPath 项目路径
 */
export const rewritePackage = async (targetPath: string): Promise<string> => {
  const targetDir = path.basename(targetPath)
  const packagePath = path.join(targetPath, 'package.json')
  if (!fs.existsSync(packagePath)) return ''

  const pkg = JSON.parse(await fs.promises.readFile(packagePath, 'utf-8'))
  pkg.name = targetDir
  await fs.promises.writeFile(packagePath, JSON.stringify(pkg, null, 2))
  return packagePath
}
